package com.yami.shop.webservice.common.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yami.shop.bean.enums.PaySeviceTypeCode;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.DataWebService;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.service.UserService;
import com.yami.shop.webservice.common.service.WapiUserService;
import com.yami.shop.webservice.common.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * @author zhangchaoqun
 * @date 2021-10-13
 */
@Service
public class WapiUserServiceImpl implements WapiUserService
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ShopConfig shopConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private DataWebService dataWebService;
    @Override
    public Map<String, Object> getWapiUserIdByCardId(String idNumber) {
        if(StrUtil.isEmpty(idNumber)){
            throw new MailException("参数不能为空");
        }
        String userType = "02";//个人
        //获取请求内容
        Map<String, String> map = new HashMap<>();
        map.put("certNo",idNumber);
        map.put("userType",userType);
        // 组装外层通用参数 发起审核通知
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info(idNumber+"用户获取恒生登录编号参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id1,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject ress = jsonObject.getJSONObject("data");
                    return ((Map<String,Object>)ress);
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public Map<String, Object> getLoginImg(String token) throws MailException {
        if(StrUtil.isEmpty(token)){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        //获取请求内容
        Map<String, String> map = new HashMap<>();
        map.put("token",token);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("获验恒生证码地址"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id2,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        // 组装外层通用参数 发起审核通知
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject ress = jsonObject.getJSONObject("data");
                return ((Map<String,Object>)ress);
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public Map<String, Object> wapiLogin(String userId, String pwdCode, String token, String checkCode, HttpServletRequest request) throws MailException {
        if(StrUtil.isEmpty(userId)||StrUtil.isEmpty(pwdCode)||StrUtil.isEmpty(token)||StrUtil.isEmpty(checkCode)){
            throw new MailException("参数不全");
        }
        //基础参数
        Map<String, String> map = new HashMap<>();
        map.put("bizType","mallClient");
        map.put("userAccount",userId);
        map.put("pwdCode",pwdCode);
        map.put("loginIp", IpUtil.getIpAddr(request));
        map.put("token",token);
        map.put("checkCode",checkCode);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所用户编码即登录账户参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id3,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject ress = jsonObject.getJSONObject("data");
                return ((Map<String,Object>)ress);
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public Map<String, Object> wapiLoginAndSave(String ourUserId,String idNumber,String userAccount, String pwdCode, String token, String checkCode, HttpServletRequest request) throws MailException {
        if(StrUtil.isEmpty(pwdCode) || StrUtil.isEmpty(token) || StrUtil.isEmpty(checkCode) || StrUtil.isEmpty(userAccount)){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        Map<String, String> map = new HashMap<>();
        map.put("bizType","mallClient");
        map.put("userAccount",userAccount);
        map.put("pwdCode",pwdCode);
        map.put("loginIp", IpUtil.getIpAddr(request));
        map.put("token",token);
        map.put("checkCode",checkCode);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所用户编码即登录账户参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id3,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject res = jsonObject.getJSONObject("data");
                //通过登录后返回的用户id获取证件号和状态
                Map<String, Object>  resMap = null;
                try{
                     resMap =  getWapiCardIdByUserId(res.getString("userId"));
                }catch (Exception e){
                    throw new MailException("获取用户证件号码异常");
                }
                if("6".equals(resMap.get("status").toString())){
                    throw new MailException("用户信息待认证，请去海文交app/pc端认证");
                }
                if("2".equals(resMap.get("status").toString())){
                    throw new MailException("用户信息正在审核中，请稍后再试");
                }
                if("4".equals(resMap.get("status").toString())){
                    throw new MailException("用户已被禁用");
                }
                if("7".equals(resMap.get("status").toString())){
                    throw new MailException("用户已被锁定");
                }
                if("5".equals(resMap.get("status").toString())){
                    throw new MailException("用户已被注销");
                }
                if("1".equals(resMap.get("status").toString())){
                    throw new MailException("用户信息审核不通过");
                }
                if(!"3".equals(resMap.get("status").toString())){
                    throw new MailException("交易系统用户状态异常");
                }
                String idNumberOut = "";
                //个人
                res.put("status",resMap.get("status"));
                if("mchtType02".equals(resMap.get("partCategories1"))){
                    res.put("certNo",resMap.get("certNo"));
                    idNumberOut = (String)resMap.get("certNo");
                }else{
                    // 企业
                    if("1".equals(resMap.get("partCategories"))){
                        //判断是三证一体
                        res.put("certNo",resMap.get("creditCodeCard"));
                        idNumberOut = (String)resMap.get("creditCodeCard");
                    }else if("0".equals(resMap.get("partCategories"))){
                        //否
                        res.put("certNo",resMap.get("certNo"));
                        idNumberOut = (String)resMap.get("certNo");
                    }else{
                        throw new MailException("企业用户获取数据异常");
                    }
                }
                //查询证件号
               if(!idNumberOut.equals(idNumber)){
                    throw new MailException("该账号的证件号与用户实名证件号不一致，请更换账号！");
                }
                String account = getAccountByUserIdAndMall(res.getString("userId"));
                User user = new User();
                user.setUserId(ourUserId);
                user.setSettleAccount(account);
                user.setSettleAccountName((String) resMap.get("partFullName"));
                //身份证绑定账号
                userService.updateById(user);
                res.put("settleAccount",resMap.get("account"));
                res.put("idNumber",idNumber);
                return (Map<String,Object>)res;
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public Map<String, Object> getWapiCardIdByUserId(String userId) throws MailException {
        if(StrUtil.isEmpty(userId)){
            throw new MailException("参数不能为空");
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId",userId);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所接口：用户获取证件号参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id4,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                JSONObject ress = jsonObject.getJSONObject("data");
                return ((Map<String,Object>)ress);
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public Boolean checkPayPosswordByUserIdAndPwd(String userId, String pwd) throws MailException {
        if(StrUtil.isEmpty(userId)||StrUtil.isEmpty(pwd)){
            throw new MailException("参数不全");
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId",userId);
        map.put("pwdCode",pwd);
        map.put("pwdType","payPwd");
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所接口用户支付密码验证参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id5,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                return jsonObject.getBoolean("data");
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public String getAccountByUserIdAndMall(String userId) throws MailException {
        if(StrUtil.isEmpty(userId)){
            throw new MailException("参数不能为空");
        }
        Map<String, String> map = new HashMap<>();
        map.put("userId",userId);
        map.put("marketCode",PaySeviceTypeCode.marketHNDX);
        map.put("pageCount","20");
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所接口用户账号参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id6,map);
       JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                String settleAccount = jsonObject.getString("data");
                return settleAccount;
            }else {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }



    @Override
    public void sendsms(String phone) throws MailException {
        if(StrUtil.isEmpty(phone)){
            throw new MailException("参数不能为空");
        }
        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所接口发短信参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id17,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE!=jsonObject.getInteger("code")) {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public String updataImg(Map<String, String> map) throws MailException {
        String name= map.get("uploadPath");
        if(StrUtil.isEmpty(map.get("uploadPath"))||StrUtil.isEmpty(map.get("uploadFile"))||StrUtil.isEmpty(map.get("uploadSize"))){
            throw new MailException("参数不能为空");
        }
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所接口上传文件参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id18,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                return jsonObject.getString("data");
            }else{
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public String getServiceUser(String phone) throws MailException {
        if(StrUtil.isEmpty(phone)){
            throw new MailException("参数不能为空");
        }
        //基础参数
        Map<String, String> map = new HashMap<>();
        map.put("phone",phone);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所接口获取服务商code参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id16,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE==jsonObject.getInteger("code")) {
                return jsonObject.getString("data");
            }else{
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }
    }

    @Override
    public void wapiRegister(String password, String account, String regChkCode, String cellPhone, String imgAttach2, String imgAttach7,String userId) throws MailException {
        if(userId==null){
            throw new MailException("获取用户失败");
        }
        User user = userService.getUserByUserId(userId);
        String phone = shopConfig.getHwjServicePhone();
        String code = getServiceUser(phone);
        //基础参数
        Map<String, String> map = new HashMap<>();
        map.put("account",account);
        map.put("password",password);
        map.put("regChkCode",regChkCode);
        map.put("cellPhone",cellPhone);
        map.put("partFullName",user.getRealName());
        map.put("certNo",user.getIdNumber());
        map.put("imgAttach2",imgAttach2);
        map.put("imgAttach7",imgAttach7);
        map.put("parentRelateId",code);
        String apiGatewayUrl = shopConfig.getApiGatewayUrl()+"/webservice/outapi/";
        log.info("交易所接口获取服务商code参数"+JSON.toJSONString(map));
        String result = dataWebService.hutoolPostWebService(apiGatewayUrl + PaySeviceTypeCode.function_id15,map);
        JSONObject jsonObject =  JSON.parseObject(result);
        if (null != jsonObject) {
            if (Constant.SUCCESS_CODE!=jsonObject.getInteger("code")) {
                log.error(jsonObject.getString("msg"));
                throw new MailException(jsonObject.getString("msg"));
            }
        }else {
            log.error("第三方发起接口返回空");
            throw new MailException("第三方发起接口返回空");
        }

    }

}
